Appendix A — Dimensions of matrices

To check the dimensions of a matrix (or an array), we use the function dim(). For matrices, this will return a vector of length 2 where the first value is the number of rows and the second value is the number of columns.

For example we can see that M1 has 6 rows and 4 columns using the following code.

dim(M1)
[1] 6 4

When extracting an entire row or column using [ ], the object that R returns is a vector rather than a matrix. This means that we can’t use some functions that only work for matrices (or arrays).

For example, the code below returns the value NULL when using the dim() function. dim() should return the dimensions of an array, but since the extracted row for births in Edinburgh is a vector, there are no dimensions to return.

dim(births["Edinburgh", ])
NULL

If we want to know how many elements are in a vector, we use the function length().

length(births["Edinburgh", ])
[1] 3

We can force the output from subseting a matrix/array to be a matrix/array by including a third argument, drop = FALSE, within the square brackets to keep the returned row as a matrix/array.

dim(births["Edinburgh", , drop = FALSE])
[1] 1 3

Now we can see that the row is seen as a 1 \(\times\) 3 matrix by R.